package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @auther falls_vc
 * description:
 * @date 2025/5/21  11:04
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localPath;
    @Override
    public String savePicture(MultipartFile multipartFile) {
        // 1. 创建路径
        File file=new File(localPath);
        if(!file.exists()) {
            file.mkdirs();
        }
        // 2. 生成自定义文件名
        String fileName=multipartFile.getOriginalFilename();
        assert file != null;
        String suffix =fileName.substring(fileName.lastIndexOf('.'));

        fileName= UUID.randomUUID()+suffix;

        // 3. 上传文件
        try {
            multipartFile.transferTo(new File(localPath+"/"+fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }


        return fileName;
    }
}
